package com.fnst.caesar.servlet;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;

import com.fnst.caesar.bean.*;
import com.fnst.caesar.util.*;

import org.apache.commons.fileupload.*;

/**
 * Servlet implementation class ImportStudent_Servlet
 */
public class ImportStudent_Servlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ImportStudent_Servlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		doPost(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
		String flag = request.getParameter("excel");
		Properties p = new Properties();
		p.load(this.getClass().getResourceAsStream("/com/fnst/caesar/importStudent.properties"));
		
		int col = Integer.parseInt(p.getProperty("col"));
		int skip = Integer.parseInt(p.getProperty("skip"));
		
		if(flag == null)
		{
			request.getRequestDispatcher("/WEB-INF/WEB/Input_Student.jsp").forward(request, response);
			return;
		}
		else
		{
			SqlSessionFactory ssf = SqlFactoryUtil.getSqlSessionFactory(request);
			SqlSession sqlSessionSelect = ssf.openSession();
			try
			{
				String rootPath = request.getRealPath(File.separator);
				String userPath = "tmp" + File.separator;
				String fullPath = rootPath + userPath;
				File upDir = new File(fullPath);
				if (!upDir.exists())
				{
					upDir.mkdirs();
				}	
				DiskFileUpload fup = new DiskFileUpload();
				fup.setSizeMax(10 * 1024 * 1024);
				fup.setSizeThreshold(1024 * 1024);
				fup.setHeaderEncoding("UTF-8");
				List fileItems = null;
				
				fileItems = fup.parseRequest(request);
				for(Object o:fileItems)
				{
					FileItem fi = (FileItem)o;
					if(fi.isFormField())
					{
						String content = fi.getString("UTF-8");
						String fieldName = fi.getFieldName();
						request.setAttribute(fieldName, content);
					}
					else
					{
						String pathSrc = fi.getName();
						int start = pathSrc.lastIndexOf(File.separator);
						int end = pathSrc.lastIndexOf(".");
						String originFileName = pathSrc.substring(start+1);
						String extra = pathSrc.substring(end+1);
						if(!extra.equalsIgnoreCase("xls"))
						{
							request.setAttribute("error", "1");
							request.getRequestDispatcher("/WEB-INF/WEB/Input_Student.jsp").forward(request, response);
							return;
						}
						else
						{
							File finalPath = new File(upDir, originFileName);
							fi.write(finalPath);
							
							String truePath = upDir+File.separator+originFileName;
							List excelData = ExcelUtil.importExcel(truePath, col, skip);
							List<ApplyInfo_Bean> result = new ArrayList<ApplyInfo_Bean>();
							List<ApplyInfo_Bean> invalid = new ArrayList<ApplyInfo_Bean>();
							
							File f = new File(truePath);
							if(f.exists())
							{
								f.delete();
							}
							
							for(Object tmp:excelData)
							{
								String[] oneRow = (String[]) tmp;
								ApplyInfo_Bean aib = new ApplyInfo_Bean(oneRow[0], oneRow[1], oneRow[2]);
								UserBasic_Bean ubb = (UserBasic_Bean)sqlSessionSelect.selectOne("com.fnst.caesar.mapper.selectUserBasicByUserId", aib.getUser_id());
								if(ubb == null)
								{
									invalid.add(aib);
								}
								else
								{
									result.add(aib);
								}
							}
							sqlSessionSelect.commit();
							sqlSessionSelect.close();
							SqlSession sqlSessionInsert = ssf.openSession(ExecutorType.BATCH, false);
							sqlSessionInsert.insert("com.fnst.caesar.mapper.insertManyApplyInfo", result);
							sqlSessionInsert.commit();
							sqlSessionInsert.close();
							
							request.setAttribute("badList", invalid);
							request.getRequestDispatcher("/WEB-INF/WEB/Input_Student.jsp").forward(request, response);
						}
					}
				}
			}
			catch (FileUploadException e)
			{
				// TODO Auto-generated catch block
				System.out.print(e.getMessage());
				request.setAttribute("error", "2");
				request.getRequestDispatcher("/WEB-INF/WEB/Input_Student.jsp").forward(request, response);
			}
			catch (Exception e)
			{
				System.out.print(e.getMessage());
				request.setAttribute("error", "2");
				request.getRequestDispatcher("/WEB-INF/WEB/Input_Student.jsp").forward(request, response);
			}
		}
	}
	
}
